
package com.example.filetransfer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.filetransfer.FileTransferService.MyBinder;
import com.example.filetransfer.connection.ClientListener;
import com.example.filetransfer.connection.ClientListener.Server;
import com.example.filetransfer.connection.ConnectionManager.OnConnectedListener;

import java.util.List;

public class MainUi extends Activity {
    private static final int REFRESH_LIST_VIEW = 1;
    private static final int REFRESH_UI = 2;
    private static final int REFRESH_TIME = 2 * 1000;

    private FileTransferService mFileTransferService;
    private Button mConnectButton;
    private HostAdapter mHostListAdapter;
    private ListView mHostList;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_ui);
        mConnectButton = (Button) findViewById(R.id.request_connect);
        mConnectButton.setOnClickListener(mClickConnectListener);

        mHostList = (ListView) findViewById(R.id.host_list);
        mHostListAdapter = new HostAdapter();
        mHostListAdapter.setData(getConnectedHost());
        mHostList.setAdapter(mHostListAdapter);
        mHostList.setOnItemClickListener(mHostItemClick);

        mProgressBar = (ProgressBar) findViewById(R.id.progress);
        Intent intent = new Intent("com.yadong.test.syncfrompc");
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private OnClickListener mClickConnectListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mFileTransferService != null) {
                requestConnection();
            }
        }
    };

    private void requestConnection() {
        mFileTransferService.requestConnection();
        mProgressBar.setVisibility(View.VISIBLE);
        mConnectButton.setEnabled(false);
        mHandler.sendEmptyMessageDelayed(REFRESH_UI, REFRESH_TIME);
    }

    protected void onStart() {
        super.onStart();
        if (mFileTransferService != null) {
            requestConnection();
        }
    };

    private class HostAdapter extends BaseAdapter {
        private List<Server> servers;
        private LayoutInflater layoutInflater;

        public HostAdapter() {
            this.layoutInflater = LayoutInflater.from(MainUi.this);
        }

        public void setData(List<Server> servers) {
            this.servers = servers;
        }

        @Override
        public int getCount() {
            return servers == null ? 0 : servers.size();
        }

        @Override
        public Object getItem(int position) {
            return servers == null && servers.size() > position ? null : servers.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView view = null;
            if (convertView != null) {
                view = (TextView) convertView;
            } else {
                view = (TextView) layoutInflater.inflate(android.R.layout.simple_list_item_1, null);
                view.setGravity(Gravity.CENTER);
            }
            view.setText(servers.get(position).ip + ":" + servers.get(position).port);
            return view;
        }
    }

    private OnItemClickListener mHostItemClick = new OnItemClickListener() {
        public void onItemClick(android.widget.AdapterView<?> view, View arg1, int index, long arg3) {
            final Server server = (Server) mHostListAdapter.getItem(index);
            mFileTransferService.startConnection(server, new OnConnectedListener() {
                @Override
                public void onConnect() {
                    Intent intent = new Intent(MainUi.this, MainActivity.class);
                    intent.putExtra("ip", server.ip);
                    intent.putExtra("port", server.port);
                    startActivity(intent);
                }
            });
        };
    };

    private List<Server> getConnectedHost() {
        if (mFileTransferService == null) {
            return null;
        }
        return mFileTransferService.getServerList();
    }

    private void refreshListView() {
        mHostListAdapter.setData(getConnectedHost());
        mHostListAdapter.notifyDataSetChanged();
    }

    private void refreshUI() {
        mConnectButton.setEnabled(true);
        mProgressBar.setVisibility(View.GONE);
        mHandler.removeMessages(REFRESH_UI);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_LIST_VIEW:
                    refreshListView();
                    break;
                case REFRESH_UI:
                    refreshUI();
                    break;
                default:
                    break;
            }
        };
    };

    private ClientListener mClientListener = new ClientListener() {
        @Override
        public void onNewClientAccept(Server server) {
            mHandler.sendEmptyMessage(REFRESH_LIST_VIEW);
            mHandler.sendEmptyMessage(REFRESH_UI);
        }

    };

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mFileTransferService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mFileTransferService = ((MyBinder) service).getService();
            mFileTransferService.setClientListener(mClientListener);
        }
    };
}
